package com.offcn.utils;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * dbutils封装了对jdbc的操作，BaseDao是对数据库进行操作
 */
public class BaseDao {
    //定义变量，QueryRunner中提供对sql语句操作的API
    QueryRunner qr;
    {
        qr = new QueryRunner();
    }
    //新增 删除  修改
    public int update(String sql,Object... params){
        int row = 0;
        try {
            //获取连接,输入sql语句,操作参数,update是更新的意思
            row = qr.update(C3p0Utils.getConnection(), sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            C3p0Utils.release();
        }
        return row;
    }
    //查询单条记录
    public <T>T findSingle(String sql,Class<T> clazz,Object... params){
        T t = null;
        try {
            //query是dbutils下QueryRunner封装的查询方法
            //BeanHandler将结果集第一条记录封装到指定的javaBean中
            t = qr.query(C3p0Utils.getConnection(),sql,new BeanHandler<>(clazz),params);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            C3p0Utils.release();
            //归还连接
        }
        return t;
    }

    //查询多条记录
    public <T>List<T> findObjs (String sql,Class<T> clazz,Object... params){
        List<T> ts = null;
        try {
            //BeanListHandler将结果集每条记录封装到指定的javaBean中
            ts = qr.query(C3p0Utils.getConnection(),sql,new BeanListHandler<>(clazz),params);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //归还连接
            C3p0Utils.release();
        }
        return ts;
    }
    //查询数量
    public int findCount (String sql){
        Long count = 0l;
        try {
            //ScalarHandler用于单列数据查询，便于计数
            count = (Long)qr.query(C3p0Utils.getConnection(), sql, new ScalarHandler());
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            C3p0Utils.release();
        }
        return count.intValue();
        //强转整型
    }

}
